<?php

namespace app\agent\controller;

use app\admin\model\Config;
use app\model\AdminAgent;
use app\model\Withdrawal;
use app\model\Withdrawal as WithdrawalModel;
use app\common\controller\Adminbase;
use app\service\AgentService;
use think\Db;
use util\Logger;

class Income extends Adminbase
{
    public function index()
    {
        $model = 'Withdrawal';
        $agent = AgentService::getAgentInfo(UID);

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $query       = WithdrawalModel::where($map)
                ->where('user_id', $agent['id'])
                ->where('type', 2);
            $count_query = clone $query;

            $list   = $query->field('*')
                ->append(['status_text', 'withdrawal_status_text', 'image'])
                ->with(['user'])
                ->withAttr('withdrawal_money', function ($value) {
                    return $value ? number_format($value / 100, 2) : "0.00";
                })
                ->page($page, $pageSize)
                ->order('id desc')
                ->select();
            $total  = $count_query->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }
        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setLayerBtn([
                ['title' => '提现', 'url' => url('withdrawal')]
            ])
            ->setDataUrl()
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDelBtn(false)
            ->setSwitchTpl('amplifyTpl', 'image')
            ->setModel($model)
            ->setLimit()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('name', '收款人姓名')
            ->addTableColumn('image', '收款码图片', '', '#amplifyTpl')
            ->addTableColumn('withdrawal_money', '提现金额' . '(元)')
            ->addTableColumn('status_text', '审核状态')
            ->addTableColumn('withdrawal_status_text', '提现状态')
            ->addTableColumn('create_time', '申请时间')
            ->returnForm();

        $total_money = $agent['total_money'] > 0 ? number_format($agent['total_money'] / 100, 2) : "0.00";
        $money       = $agent['money'] > 0 ? number_format($agent['money'] / 100, 2) : "0.00";
        $this->assign('text', "总收益：{$total_money}元，余额：{$money}元");
        $this->assign('module', 'user');
        return $this->fetch('admin@common/lists');
    }

    /**
     * 提交提现
     * @return \think\response\Json
     * @throws \Random\RandomException
     */
    public function withdrawal()
    {
        //平台总收益
        $agent = AdminAgent::where('admin_id', UID)
            ->field('id, money')
            ->find();
        if ($agent['money'] <= 0) {
            $this->error('提现余额不足');
        }
        if (request()->isPost()) {
            $name             = request()->post('name');
            $withdrawal_money = request()->post('money');
            $channel          = request()->post('channel');
            $QRCode           = request()->post('QRCode');
            $bankName         = request()->post('bankName');
            $bankAddress      = request()->post('bankAddress');
            $cardNo           = request()->post('cardNo');
            $cellPhoneNumber  = request()->post('phone');
            $is_china         = request()->post('is_china', 1);

            $withdrawal_money = intval($withdrawal_money * 100); //单位：分
            if ($agent['money'] - $withdrawal_money < 0) {
                return json(['code' => -1, 'msg' => '提现失败，用户余额不足']);
            }

            if (empty($name) || empty($withdrawal_money)) {
                return json(['code' => -1, 'msg' => '请填写收款人姓名和提现金额']);
            }
            if ($channel == 0 && (empty($bankName) || empty($cardNo) || empty($cellPhoneNumber))) {
                return json(['code' => -1, 'msg' => '银行信息缺少']);
            }
            if ($channel == 1 && empty($QRCode)) {
                return json(['code' => -1, 'msg' => '必须上传收款码']);
            }
            $QRCode = get_file_path($QRCode, 1);
            if ($channel == 0) {
                $account = [
                    'name'            => $name,
                    'money'           => $withdrawal_money,
                    'bankName'        => $bankName,
                    'cardNo'          => $cardNo,
                    'cellPhoneNumber' => $cellPhoneNumber,
                    'bankAddress'     => $bankAddress,
                ];
            } else {
                $QRCode  = get_file_path($QRCode, 1);
                $account = [
                    'name'  => $name,
                    'money' => $withdrawal_money,
                    'image' => $QRCode,
                ];
            }

            try {
                Db::startTrans();
                $withdrawal_charge = intval(Config::where('name', 'withdrawal_agent_charge')->value('value')) ?: 0;
                $charge_money      = $withdrawal_money * $withdrawal_charge / 100;
                $total_money       = $agent['money'];
                $res               = Withdrawal::create([
                    'user_id'           => $agent['id'],
                    'type'              => 2,
                    'name'              => $name,
                    'channel'           => $channel,
                    'withdrawal_money'  => $withdrawal_money, //单位：分
                    'money'             => ($withdrawal_money - $charge_money), //单位：分
                    'withdrawal_charge' => $withdrawal_charge,
                    'charge_money'      => $charge_money,
                    'account'           => json_encode($account, JSON_UNESCAPED_UNICODE),
                    'status'            => 0,
                    'withdrawal_status' => 0,
                    'before_money'      => $total_money,
                    'after_money'       => $total_money - $withdrawal_money,
                ]);
                $agent_res         = AdminAgent::where('id', $agent['id'])
                    ->update([
                        'money' => $total_money - $withdrawal_money,
                    ]);
                if ($res && $agent_res) {
                    Db::commit();
                    return json(['code' => 0, 'msg' => '提现成功']);
                }
                Db::rollback();
                return json(['code' => -1, 'msg' => '提现失败']);

            } catch (\Exception $e) {
                $log = [
                    'message' => $e->getMessage(),
                    'file'    => $e->getFile(),
                    'line'    => $e->getLine(),
                ];
                Logger::error('提交提现失败', $log);
                return json(['code' => -1, 'msg' => '提现失败']);
            }
        }

        $this->assign([
            'channel' => [0 => '银行卡', 1 => '支付宝', 2 => '微信'],
            'info'    => [
                'type'  => 0,
                'total' => number_format($agent['money'] / 100, 2),
            ],
        ]);
        return $this->fetch('agent/withdrawal');
    }

    /**
     * 判断银行卡号是国内还是国外
     */
    public function check(string $cardNo)
    {
        // 移除所有非数字字符
        $cardNo = preg_replace('/[^0-9]/', '', $cardNo);

        // 校验银行卡号长度（通常为12到19位）
        if (strlen($cardNo) < 12 || strlen($cardNo) > 19) {
            return json(['code' => -1, 'msg' => '无效卡号']);
        }

        // 校验银行卡号是否有效（Luhn算法）
        if (!$this->isValidCardNumber($cardNo)) {
            return json(['code' => -1, 'msg' => '无效卡号']);
        }


        // 判断是否为国内银联卡（以62开头）
        if (str_starts_with($cardNo, '62')) {
            return json(['code' => 0, 'msg' => 'success', 'data' => 1]);
        }
        return json(['code' => 0, 'msg' => 'success', 'data' => 0]);
    }

    /**
     * 使用Luhn算法校验银行卡号是否有效
     * @param string $cardNumber 银行卡号
     * @return bool
     */
    public function isValidCardNumber(string $cardNumber): bool
    {
        $sum    = 0;
        $length = strlen($cardNumber);
        for ($i = 0; $i < $length; $i++) {
            $digit = (int)$cardNumber[$length - $i - 1];
            if ($i % 2 === 1) {
                $digit *= 2;
                if ($digit > 9) {
                    $digit -= 9;
                }
            }
            $sum += $digit;
        }
        return $sum % 10 === 0;
    }

}
